package com.apes.fico.masterdata.gl.service;

import com.apes.fico.masterdata.gl.model.AccountingChartType;
import com.apes.fico.masterdata.gl.respository.AccountingChartTypeRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName AccountingChartTypeService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/2/18 9:52
 * @Version 1.0
 **/
@Service("accountingChartTypeService")
public class AccountingChartTypeService extends DomainService {
    @Autowired
    private AccountingChartTypeRepository accountingChartTypeRepository;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    public AccountingChartType save(SimpleRequest request) {
        AccountingChartType accountingChartType = request.getO(AccountingChartType.class);
        accountingChartType.setCreateDate(new Date());
        return accountingChartTypeRepository.saveAndFlush(accountingChartType);
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    public AccountingChartType update(SimpleRequest request) {
        checkData(request);
        AccountingChartType accountingChartType = request.getO(AccountingChartType.class);
        accountingChartType.setUpdateDate(new Date());
        return accountingChartTypeRepository.saveAndFlush(accountingChartType);
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        checkData(request);
        AccountingChartType accountingChartType = request.getO(AccountingChartType.class);
        accountingChartTypeRepository.delete(accountingChartType.getId());
        return "删除成功";
    }

    /**
     * 检查
     *
     * @param request
     */
    private void checkData(SimpleRequest request) {
        AccountingChartType accountingChartType = accountingChartTypeRepository.findOne((String) request.get("id"));
        if (accountingChartType == null) throw new RuntimeException("科目类型" + accountingChartType.getId() + "不存在");
        if (accountingChartType.getVersion() != (int) request.get("version"))
            throw new RuntimeException("科目类型" + accountingChartType.getId() + "已更新或已删除");
    }
}
